<?php

namespace App\Http\Middleware;

use Closure;
use Aitifen\Library\Xxtea\Xxtea;
use Illuminate\Support\Facades\Config;

class WebLoginMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token   = isset($_COOKIE['STEAM-ACCESS-TOKEN']) ? $_COOKIE['STEAM-ACCESS-TOKEN'] : '';
        $appData = isset($_COOKIE['app_data']) ? $_COOKIE['app_data'] : '';
        if (empty($token)) {
            $token   = $request->header('STEAM-ACCESS-TOKEN');
        }
        $accessList = array(
            // 跳过登录验证 一律小写
            '/api/users/getloginstatus',
            '/api/teacher/setteachertoken',
            '/api/student/setstudenttoken',
            '/api/backend/users/getmobileagency',
        );
        // 获取当前访问路由
        $path = strtolower($_SERVER['REQUEST_URI']);
        if ((in_array($path, $accessList) == false) && empty($token)) {
            $returnData = [
                'code' => 1001,
                'message' => '用户AccessToken不存在或已过期!',
                'data' => [],
            ];
            echo json_encode($returnData,JSON_UNESCAPED_UNICODE);exit;
        }

        if(empty($appData) && $path != '/api/users/getloginstatus') {
            return redirect('/api/users/getLoginStatus');
        }
        return $next($request);
    }
}